// Created: Dec 11, 2014
//
// Author: wjinwen.1988@gmail.com

#ifndef CHI_BASE_MAIN_H
#define CHI_BASE_MAIN_H
#include "chi/mutex.h"
#include "chi/condition.h"

#include <string>

// 屏蔽gflags的usage信息
#define STRIP_FLAG_HELP 1
#include <gflags/gflags.h>

// 是否启动守护进程
DECLARE_bool(daemon);
// 配置文件
DECLARE_string(conf_file);
// PID文件，如不设置PID文件存放在log目录下
DECLARE_string(pid_file);

namespace chi {
class BaseMain {
 public:
  BaseMain();
  virtual ~BaseMain();

  int main(int argc, char* argv[]);

  static BaseMain* instance();

  int HandleInterrupt(int sig);

  void stop();

  virtual int run(int argc, char* argv[]) = 0;

  // get pid file path
  virtual const char* pid_file_path() { return pid_file_path_.c_str(); }

  virtual int Reinitilize() { return 0; }
  
  virtual bool destroy() = 0;

  virtual void SetUsageMessage();
  virtual void SetVersion();

  bool stop_;
  bool is_glog_init_;
  std::string pid_file_path_;
  std::string log_dir_;
  int log_level_;  // 日志级别（0:INFO 1:WARNING 2:ERROR 3:FATAL)
  int max_log_size_;  // 日志文件最大大小(MB)

 private:
  int shutdown();
  int WaitForShutdown();
  int start(int argc, char* argv[], const bool deamon);

  int InitializePidFile(const char* app_name);
  int InitializeGlog(const char* app_name);
  void RemovePidFile(const char* app_name);

  MutexLock mutex_;
  Condition cond_;
  static BaseMain* instance_;
};

}  // namespace chi

#endif  // CHI_BASE_MAIN_H
